import os
import subprocess

from docx import Document
from Data import search_file
from Data import loadDiagnosisOrMaintenance_model_number_catalogue
from Data import loadDiagnosisOrMaintenance_model
from Data.Chinese import model
from Data.Chinese import oneClickPublishing

scg_cref = None
is_scg_cref = None
model_name = None
file_name = None
bianhao = None
sysop_flag = False
updated_paths = []


# 模块编号
def model_number(flag, is_only_dir):
    global updated_paths
    global sysop_flag
    res = model.module_level_number(flag, is_only_dir)
    # filepaths = model.module_level_number(flag, is_only_dir)
    if res == "-1":
        return "-1"
    sysop_flag = res[1]
    if sysop_flag is True or sysop_flag is False:
        filepaths = res[0]
    else:
        filepaths = res

    # filepaths = res[0]
    if filepaths == "-1":
        return "-1"
    updated_paths = filepaths
    # 创建目录结构映射
    directory_map = {}
    for filepath in filepaths:
        # print(filepath)
        if "封面" in filepath and "扉页" in filepath:
            continue
        if "PDF" in filepath:
            continue
        if "维护" in filepath and "诊断" in filepath:
            res = loadDiagnosisOrMaintenance_model.diagnosis_or_maintenance(flag, is_only_dir, filepaths)
            if res == "-1":
                return "-1"
            sysop_flag = res[1]
            # if sysop_flag:
            #     return sysop_flag

            filepaths = res[0]
            if filepaths == "-1":
                return "-1"
            # filepaths = loadDiagnosisOrMaintenance_model.diagnosis_or_maintenance(flag, is_only_dir, filepaths)
            loadDiagnosisOrMaintenance_model_number_catalogue.diagnosis_or_maintenance(filepaths, flag, sysop_flag)
            if sysop_flag:
                pass
            else:
                sysop_flag = loadDiagnosisOrMaintenance_model_number_catalogue.sysop_flag
                # print(sysop_flag)
                updated_paths = loadDiagnosisOrMaintenance_model_number_catalogue.updated_paths
            return
        parts = filepath.split('\\')
        if len(parts) >= 4:  # 确保路径深度足够
            first_level = parts[-3]  # 一级目录（如：命令参考）
            second_level = parts[-2]  # 二级目录（如：可靠性）
            # 初始化一级目录
            if first_level not in directory_map:
                directory_map[first_level] = {}
            # 将文件添加到对应的二级目录
            if second_level not in directory_map[first_level]:
                directory_map[first_level][second_level] = []
            directory_map[first_level][second_level].append(filepath)
    # 处理每个目录
    for first_level, second_levels in directory_map.items():
        # print(f"\033[93m处理一级目录: {first_level}\033[0m")
        for second_level, files in second_levels.items():
            print(f"\033[93m正在处理: {first_level}->{second_level}\033[0m")
            # 查找该目录下的扉页
            feiye_path = None
            for file in files:
                if search_feiye(file) != "-1":
                    feiye_path = file
                    break
            if feiye_path:
                # print(f"找到扉页: {os.path.basename(feiye_path)}")
                split_filepath(feiye_path)
                # 这里可以添加处理扉页的逻辑
                content_list = open_feiye(feiye_path, first_level, second_level)
                sort_list = sort_content(content_list)
                filename_montage_list = filename_montage(sort_list)
                if flag:
                    rename_svn(filename_montage_list, feiye_path)
                else:
                    rename(filename_montage_list, feiye_path)
            else:
                print(f"\033[91m{first_level}->{second_level}：未找到扉页\033[0m")
                sysop_flag = True
    print("-------------------------")
    if sysop_flag:
        pass
    else:
        if not oneClickPublishing.sys_flag:
            print("程序执行完成！！！")
    # print("-------------------------")


def rename(value, feiye_path):
    flag = False
    global sysop_flag
    if value == "-1":
        return "-1"
    findname = []
    path = feiye_path.rsplit('\\', 1)[0]  # 获取当前扉页所在目录

    # 只获取当前目录下的文件
    current_files = []
    for file in search_file.filepath_all:
        if path in file:  # 只处理当前目录下的文件
            current_files.append(file)

    for oldfilename in current_files:
        old_path = oldfilename
        oldfilename = oldfilename.split('\\')[-1]
        oldfilename = oldfilename.rsplit('.', 1)[0]
        if "命令参考" == scg_cref:
            oldfilename = oldfilename.rsplit('命', 1)[0]
        if "配置指南" == scg_cref:
            oldfilename = oldfilename.rsplit('配', 1)[0]
        if "扉页" in oldfilename:
            if "-" in oldfilename:
                continue
            else:
                feiye_name = f'00-{oldfilename}.docx'
                os.rename(old_path, f'{path}/{feiye_name}')
        if any(char.isdigit() for char in oldfilename) and "-" in oldfilename and oldfilename.split('-')[0].isdigit():
            oldfilename = '-'.join(oldfilename.split('-')[1:]).strip()
        for i, name in enumerate(bianhao):
            # print(f'name:{name}')
            # print(f'oldfilename:{oldfilename}')
            if name == oldfilename:
                newfilename = f"{path}/{value[i]}"
                try:
                    os.rename(old_path, newfilename)
                    findname.append(name)
                    for j, updated_path in enumerate(updated_paths):
                        if old_path in updated_path:
                            updated_paths[j] = updated_path.replace(old_path, newfilename)
                    flag = True
                except Exception as e:
                    flag = False
                    print(f"重命名失败:{e}")
                    sysop_flag = True
    if flag:
        has_output = False  # 添加标记来跟踪是否有输出
        # print(f'has_output:{has_output}')
        # 检查是否有缺失文件
        missing_files = [feiye for feiye in bianhao if feiye not in findname]
        if missing_files:
            if not has_output:
                print("-------------------------")
                has_output = True
            for feiye in missing_files:
                print(f"扉页中文件缺失：{feiye}")
                sysop_flag = True
            print("-------------------------")

        # 检查不在扉页中的文件
        files_not_in_feiye = []
        for current_file in current_files:
            if "配置指南" == scg_cref:
                filename = current_file.split('\\')[-1].rsplit('.', 1)[0].rsplit('配', 1)[0]
                filename = filename.strip()
                # PIM-SMv6
                if any(char.isdigit() for char in filename) and "-" in filename and filename.split('-')[0].isdigit():
                    actual_name = '-'.join(filename.split('-')[1:]).strip()
                    if actual_name not in findname and actual_name not in bianhao and "扉页" not in filename:
                        files_not_in_feiye.append(filename)
                else:
                    if filename not in findname and filename not in bianhao and "扉页" not in filename and "~" not in filename:
                        files_not_in_feiye.append(filename)
            if "命令参考" == scg_cref:
                filename = current_file.split('\\')[-1].rsplit('.', 1)[0].rsplit('命', 1)[0]
                filename = filename.strip()
                if any(char.isdigit() for char in filename) and "-" in filename and filename.split('-')[0].isdigit():
                    actual_name = '-'.join(filename.split('-')[1:]).strip()
                    if actual_name not in findname and actual_name not in bianhao and "扉页" not in filename:
                        files_not_in_feiye.append(filename)
                else:
                    if filename not in findname and filename not in bianhao and "扉页" not in filename and "~" not in filename:
                        files_not_in_feiye.append(filename)

        # 如果有不在扉页中的文件，才输出
        if files_not_in_feiye:
            if not has_output:
                print("-------------------------")
                has_output = True
            for filename in files_not_in_feiye:
                print(f"文件不在扉页中：{filename}")
                sysop_flag = True

        # 只在有输出时显示底部分隔线
        if has_output:
            print("-------------------------")
        # print("程序执行完成！！！")
        # print("-------------------------")
    else:
        has_output = False  # 添加标记来跟踪是否有输出
        # print(f'has_output:{has_output}')
        # 检查是否有缺失文件
        missing_files = [feiye for feiye in bianhao if feiye not in findname]
        if missing_files:
            if not has_output:
                print("-------------------------")
                has_output = True
            for feiye in missing_files:
                print(f"扉页中文件缺失：{feiye}")
                sysop_flag = True
            print("-------------------------")

        # 检查不在扉页中的文件
        files_not_in_feiye = []
        for current_file in current_files:
            if "配置指南" == scg_cref:
                filename = current_file.split('\\')[-1].rsplit('.', 1)[0].rsplit('配', 1)[0]
                filename = filename.strip()
                # PIM-SMv6
                if any(char.isdigit() for char in filename) and "-" in filename and filename.split('-')[0].isdigit():
                    actual_name = '-'.join(filename.split('-')[1:]).strip()
                    if actual_name not in findname and actual_name not in bianhao and "扉页" not in filename:
                        files_not_in_feiye.append(filename)
                else:
                    if filename not in findname and filename not in bianhao and "扉页" not in filename and "~" not in filename:
                        files_not_in_feiye.append(filename)
            if "命令参考" == scg_cref:
                filename = current_file.split('\\')[-1].rsplit('.', 1)[0].rsplit('命', 1)[0]
                filename = filename.strip()
                if any(char.isdigit() for char in filename) and "-" in filename and filename.split('-')[0].isdigit():
                    actual_name = '-'.join(filename.split('-')[1:]).strip()
                    if actual_name not in findname and actual_name not in bianhao and "扉页" not in filename:
                        files_not_in_feiye.append(filename)
                else:
                    if filename not in findname and filename not in bianhao and "扉页" not in filename and "~" not in filename:
                        files_not_in_feiye.append(filename)

        # 如果有不在扉页中的文件，才输出
        if files_not_in_feiye:
            if not has_output:
                print("-------------------------")
                has_output = True
            for filename in files_not_in_feiye:
                print(f"文件不在扉页中：{filename}")
                sysop_flag = True

        # 只在有输出时显示底部分隔线
        # if has_output:
        #     print("-------------------------")
        # print("程序执行完成！！！")
        # print("-------------------------")


def rename_svn(value, feiye_path):
    flag = None
    global sysop_flag
    if value == "-1":
        return "-1"
    findname = []
    path = feiye_path.rsplit('\\', 1)[0]  # 获取当前扉页所在目录

    # 只获取当前目录下的文件
    current_files = []
    for file in search_file.filepath_all:
        if path in file:  # 只处理当前目录下的文件
            current_files.append(file)

    for oldfilename in current_files:
        old_path = oldfilename
        oldfilename = oldfilename.split('\\')[-1]
        oldfilename = oldfilename.rsplit('.', 1)[0]
        if "命令参考" == scg_cref:
            oldfilename = oldfilename.rsplit('命', 1)[0]
        if "配置指南" == scg_cref:
            oldfilename = oldfilename.rsplit('配', 1)[0]
        if "扉页" in oldfilename:
            if "-" in oldfilename:
                continue
            else:
                feiye_name = f'00-{oldfilename}.docx'
                feiye_name = f'{path}/{feiye_name}'
                svn_command = f'svn mv "{old_path}" "{feiye_name}"'
                subprocess.run(svn_command, shell=True, check=True)
        if any(char.isdigit() for char in oldfilename) and "-" in oldfilename and oldfilename.split('-')[0].isdigit():
            oldfilename = '-'.join(oldfilename.split('-')[1:]).strip()
        for i, name in enumerate(bianhao):
            if name == oldfilename:
                newfilename = f"{path}/{value[i]}"
                old_path = old_path.replace('\\', '/')
                newfilename = newfilename.replace('\\', '/')
                try:
                    if old_path == newfilename:
                        findname.append(name)  # 即使跳过也要添加到 findname
                        flag = True
                        continue
                    else:
                        svn_command = f'svn mv "{old_path}" "{newfilename}"'
                        subprocess.run(svn_command, shell=True, check=True)
                        findname.append(name)
                        for j, updated_path in enumerate(updated_paths):
                            if old_path in updated_path:
                                updated_paths[j] = updated_path.replace(old_path, newfilename)
                        flag = True
                except subprocess.CalledProcessError as e:
                    print(f"SVN重命名失败: {e}")
                    sysop_flag = True
                except Exception as e:
                    print(f"其它错误:{e}")
                    sysop_flag = True
    if flag:
        has_output = False  # 添加标记来跟踪是否有输出

        # 检查是否有缺失文件
        missing_files = [feiye for feiye in bianhao if feiye not in findname]
        if missing_files:
            if not has_output:
                print("-------------------------")
                has_output = True
            for feiye in missing_files:
                print(f"扉页中文件缺失：{feiye}")
                sysop_flag = True
            print("-------------------------")

        # 检查不在扉页中的文件
        files_not_in_feiye = []
        for current_file in current_files:
            if "配置指南" == scg_cref:
                filename = current_file.split('\\')[-1].rsplit('.', 1)[0].rsplit('配', 1)[0]
                filename = filename.strip()
                # PIM-SMv6
                if any(char.isdigit() for char in filename) and "-" in filename and filename.split('-')[0].isdigit():
                    actual_name = '-'.join(filename.split('-')[1:]).strip()
                    if actual_name not in findname and actual_name not in bianhao and "扉页" not in filename:
                        files_not_in_feiye.append(filename)
                else:
                    if filename not in findname and filename not in bianhao and "扉页" not in filename and "~" not in filename:
                        files_not_in_feiye.append(filename)
            if "命令参考" == scg_cref:
                filename = current_file.split('\\')[-1].rsplit('.', 1)[0].rsplit('命', 1)[0]
                filename = filename.strip()
                if any(char.isdigit() for char in filename) and "-" in filename and filename.split('-')[0].isdigit():
                    actual_name = '-'.join(filename.split('-')[1:]).strip()
                    if actual_name not in findname and actual_name not in bianhao and "扉页" not in filename:
                        files_not_in_feiye.append(filename)
                else:
                    if filename not in findname and filename not in bianhao and "扉页" not in filename and "~" not in filename:
                        files_not_in_feiye.append(filename)

        # 如果有不在扉页中的文件，才输出
        if files_not_in_feiye:
            if not has_output:
                print("-------------------------")
                has_output = True
            for filename in files_not_in_feiye:
                print(f"文件不在扉页中：{filename}")
                sysop_flag = True

        # 只在有输出时显示底部分隔线
        if has_output:
            print("-------------------------")
    else:
        has_output = False  # 添加标记来跟踪是否有输出

        # 检查是否有缺失文件
        missing_files = [feiye for feiye in bianhao if feiye not in findname]
        if missing_files:
            if not has_output:
                print("-------------------------")
                has_output = True
            for feiye in missing_files:
                print(f"扉页中文件缺失：{feiye}")
                sysop_flag = True
            print("-------------------------")

        # 检查不在扉页中的文件
        files_not_in_feiye = []
        for current_file in current_files:
            if "配置指南" == scg_cref:
                filename = current_file.split('\\')[-1].rsplit('.', 1)[0].rsplit('配', 1)[0]
                filename = filename.strip()
                # PIM-SMv6
                if any(char.isdigit() for char in filename) and "-" in filename and filename.split('-')[0].isdigit():
                    actual_name = '-'.join(filename.split('-')[1:]).strip()
                    if actual_name not in findname and actual_name not in bianhao and "扉页" not in filename:
                        files_not_in_feiye.append(filename)
                else:
                    if filename not in findname and filename not in bianhao and "扉页" not in filename and "~" not in filename:
                        files_not_in_feiye.append(filename)
            if "命令参考" == scg_cref:
                filename = current_file.split('\\')[-1].rsplit('.', 1)[0].rsplit('命', 1)[0]
                filename = filename.strip()
                if any(char.isdigit() for char in filename) and "-" in filename and filename.split('-')[0].isdigit():
                    actual_name = '-'.join(filename.split('-')[1:]).strip()
                    if actual_name not in findname and actual_name not in bianhao and "扉页" not in filename:
                        files_not_in_feiye.append(filename)
                else:
                    if filename not in findname and filename not in bianhao and "扉页" not in filename and "~" not in filename:
                        files_not_in_feiye.append(filename)

        # 如果有不在扉页中的文件，才输出
        if files_not_in_feiye:
            if not has_output:
                print("-------------------------")
                has_output = True
            for filename in files_not_in_feiye:
                print(f"文件不在扉页中：{filename}")
                sysop_flag = True

        # 只在有输出时显示底部分隔线
        if has_output:
            print("-------------------------")


def filename_montage(value):
    if value == "-1":
        return "-1"
    numbered_list = []
    if scg_cref == "命令参考":
        for text in value:
            text = f"{text}命令.docx"
            numbered_list.append(text)
    if scg_cref == "配置指南":
        for text in value:
            text = f"{text}配置.docx"
            numbered_list.append(text)
    return numbered_list


def sort_content(value):
    global bianhao
    if value == "-1":
        return "-1"
    bianhao = value
    # 创建新的编号后的列表
    numbered_list = []
    # 从1开始编号，使用enumerate获取索引
    for index, content in enumerate(value, 1):
        # 格式化序号为两位数（01, 02等）
        number = f"{index:02d}"
        # 拼接序号和内容
        numbered_content = f"{number}-{content}"
        numbered_list.append(numbered_content)
    filelist = numbered_list
    return numbered_list


def search_feiye(filepath):
    filename = os.path.basename(filepath)
    if "扉页" in filename:
        return filepath
    else:
        return "-1"


def open_feiye(feiye_path, first, second):
    global scg_cref
    document = Document(feiye_path)
    content_array = []
    for paragraph in document.paragraphs:
        if "配置指南" in paragraph.text and "-" in paragraph.text:
            scg_cref = "配置指南"
        if "命令参考" in paragraph.text and "-" in paragraph.text:
            scg_cref = "命令参考"
    feiye = scg_cref_is(scg_cref, first, second)
    if feiye:
        found_target = False
        for paragraph in document.paragraphs:
            if "以下章节" in paragraph.text:
                found_target = True
                continue
            if found_target and paragraph.text.strip():
                content_array.append(paragraph.text)
    else:
        return "-1"
    return content_array


def scg_cref_is(value, first, second):
    if is_scg_cref == value:
        return True
    else:
        print(f"\033[91m{first}->{second}：扉页不符规范\033[0m")
        return False


def split_filepath(filepath):
    global model_name
    global file_name
    global is_scg_cref
    is_scg_cref = filepath.split('\\')[-3]
    if any(char.isdigit() for char in is_scg_cref):
        is_scg_cref = '-'.join(is_scg_cref.split('-')[1:])
    # print(is_scg_cref)
    model_name = filepath.split('\\')[-2]
    file_name = filepath.split('\\')[-1]
    # print(f'{is_scg_cref}+{model}+{filename}')


if __name__ == '__main__':
    model_number(False, False)
